import React, { useEffect, useState } from 'react'
import { useQuery } from 'remax'
import { View } from 'remax/one'
import { cloud, navigateToMiniProgram } from 'remax/wechat'
import { Button } from 'annar'
import styles from './index.css'

const db = cloud.database()

export default () => {
  const { _id } = useQuery()
  const [miniProgram, setMiniProgram] = useState()
  const [starter, setStarter] = useState<{ wechat: string }>()
  useEffect(() => {
    ;(async () => {
      const { data: cData } = await db.collection('vote-config').get()
      if (cData && cData[0]) {
        setMiniProgram(cData[0].miniProgram)
      }
      const { data: sData } = await db
        .collection('vote-starter')
        .where({ _id })
        .get()
      if (sData && sData[0]) {
        setStarter(sData[0])
      }
    })()
  }, [])

  if (!starter || !miniProgram) {
    return null
  }

  return (
    <View className={styles.mainArea}>
      <View className={styles.desc}>您扫描了 {starter.wechat} 的二维码</View>
      <Button
        look="secure"
        size="large"
        onTap={async () => {
          await navigateToMiniProgram(miniProgram)
          const { data } = await db.collection('vote-invite').get()
          if (!data.length) {
            await db.collection('vote-invite').add({
              data: { starter, createAt: db.serverDate() },
            })
          }
        }}
      >
        进入抽奖小程序
      </Button>
    </View>
  )
}
